<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8">
      <div>
        <h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900">
          {{ $t('auth.resetPassword.title') }}
        </h2>
        <p class="mt-2 text-center text-sm text-gray-600">
          {{ $t('auth.resetPassword.description') }}
        </p>
        <p v-if="email" class="mt-1 text-center text-sm text-gray-500">
          {{ $t('auth.resetPassword.codeSentTo', { email }) }}
        </p>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="rounded-md bg-red-50 p-4">
        <div class="flex">
          <div class="flex-shrink-0">
            <ExclamationTriangleIcon class="h-5 w-5 text-red-400" aria-hidden="true" />
          </div>
          <div class="ml-3">
            <h3 class="text-sm font-medium text-red-800">
              {{ error }}
            </h3>
          </div>
        </div>
      </div>

      <form class="mt-8 space-y-6" @submit.prevent="handleResetPassword">
        <div class="space-y-4">
          <!-- 邮箱地址 -->
          <div>
            <label for="email" class="block text-sm font-medium text-gray-700">{{ $t('auth.email') }}</label>
            <input
              id="email"
              v-model="form.email"
              name="email"
              type="email"
              autocomplete="email"
              required
              class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm"
              :placeholder="$t('auth.placeholders.email')"
            />
          </div>

          <!-- 验证码 -->
          <div>
            <label for="verification_code" class="block text-sm font-medium text-gray-700">{{ $t('auth.resetPassword.verificationCode') }}</label>
            <div class="mt-1 flex space-x-2">
              <input
                id="verification_code"
                v-model="form.verification_code"
                name="verification_code"
                type="text"
                maxlength="6"
                pattern="[0-9]{6}"
                required
                class="flex-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm"
                :placeholder="$t('auth.placeholders.verificationCode')"
              />
              <button
                type="button"
                @click="resendCode"
                :disabled="sendingCode || countdown > 0"
                class="px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {{ sendingCode ? $t('auth.forgotPasswordPage.sending') : countdown > 0 ? $t('auth.resetPassword.countdown', { seconds: countdown }) : $t('auth.resetPassword.resendCode') }}
              </button>
            </div>
          </div>

          <!-- 新密码 -->
          <div>
            <label for="new_password" class="block text-sm font-medium text-gray-700">{{ $t('auth.resetPassword.newPassword') }}</label>
            <input
              id="new_password"
              v-model="form.new_password"
              name="new_password"
              type="password"
              autocomplete="new-password"
              required
              minlength="6"
              class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm"
              :placeholder="$t('auth.placeholders.newPassword')"
            />
          </div>

          <!-- 确认密码 -->
          <div>
            <label for="confirm_password" class="block text-sm font-medium text-gray-700">{{ $t('auth.resetPassword.confirmNewPassword') }}</label>
            <input
              id="confirm_password"
              v-model="form.confirm_password"
              name="confirm_password"
              type="password"
              autocomplete="new-password"
              required
              class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm"
              :placeholder="$t('auth.placeholders.confirmPassword')"
            />
          </div>
        </div>

        <div>
          <button
            type="submit"
            :disabled="isLoading || !isFormValid"
            class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <span v-if="isLoading" class="absolute left-0 inset-y-0 flex items-center pl-3">
              <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
            </span>
            {{ isLoading ? $t('auth.resetPassword.resetting') : $t('auth.resetPassword.resetButton') }}
          </button>
        </div>

        <div class="text-center space-y-2">
          <router-link
            to="/forgot-password"
            class="font-medium text-primary-600 hover:text-primary-500"
          >
            {{ $t('auth.resetPassword.backToForgot') }}
          </router-link>
          <br>
          <router-link
            to="/login"
            class="font-medium text-gray-600 hover:text-gray-500"
          >
            {{ $t('auth.resetPassword.backToLogin') }}
          </router-link>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ExclamationTriangleIcon } from '@heroicons/vue/24/outline'
import { sendVerificationCode } from '@/api/emailVerification'
import { authService } from '@/services/auth'
import { isValidEmail } from '@/utils/helpers'

const router = useRouter()
const route = useRoute()
const { t } = useI18n()

// 表单数据
const form = ref({
  email: '',
  verification_code: '',
  new_password: '',
  confirm_password: ''
})

// 状态
const isLoading = ref(false)
const sendingCode = ref(false)
const error = ref('')
const countdown = ref(0)
let countdownTimer: number | null = null

// 从路由参数获取邮箱
const email = computed(() => route.query.email as string || '')

// 表单验证
const isFormValid = computed(() => {
  return (
    isValidEmail(form.value.email) &&
    form.value.verification_code.length === 6 &&
    form.value.new_password.length >= 6 &&
    form.value.new_password === form.value.confirm_password
  )
})

// 重置密码
const handleResetPassword = async () => {
  if (!isFormValid.value) {
    error.value = t('auth.validation.checkInput')
    return
  }

  try {
    isLoading.value = true
    error.value = ''

    await authService.resetPassword({
      email: form.value.email,
      verification_code: form.value.verification_code,
      new_password: form.value.new_password
    })

    alert(t('auth.resetPassword.success'))
    router.push('/login')

  } catch (err: any) {
    error.value = err.response?.data?.message || '密碼重置失敗，請稍後重試'
  } finally {
    isLoading.value = false
  }
}

// 重新发送验证码
const resendCode = async () => {
  if (!isValidEmail(form.value.email)) {
    error.value = t('auth.validation.invalidEmail')
    return
  }

  try {
    sendingCode.value = true
    error.value = ''

    await sendVerificationCode({
      email: form.value.email,
      type: 'reset_password'
    })

    alert(t('auth.forgotPasswordPage.codeSent'))

    // 开始倒计时
    countdown.value = 60
    countdownTimer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer!)
        countdownTimer = null
      }
    }, 1000)

  } catch (err: any) {
    error.value = err.response?.data?.message || '發送驗證碼失敗'
  } finally {
    sendingCode.value = false
  }
}

onMounted(() => {
  // 如果有邮箱参数，自动填入
  if (email.value) {
    form.value.email = email.value
  }
})

onUnmounted(() => {
  // 清理倒计时器
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>
